package com.itheima.service.mongo.impl;

import com.itheima.domain.mongo.UserLike;

import com.itheima.service.mongo.UserLikeService;
import org.apache.dubbo.config.annotation.DubboService;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

@DubboService
public class UserLikeServiceImpl implements UserLikeService {
    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 保存用户的喜欢(第一次访问这个方法 和 第N次访问这个方法)
     * @param loginUserId
     * @param userLikeId
     */
    @Override
    public void saveUserLike(Long loginUserId, Long userLikeId) {
        //1.判断我是否喜欢过这个人
        Query query = new Query(
                Criteria.where("userId").is(loginUserId)
                .and("likeUserId").is(userLikeId)
        );
        UserLike userLike = mongoTemplate.findOne(query, UserLike.class);

        //2.如果没有喜欢 添加喜欢的记录
        if(userLike == null){
            //2.1 创建对象
            userLike  = new UserLike();
            //2.2 封装数据
            userLike.setCreated(System.currentTimeMillis());
            userLike.setUserId(loginUserId);
            userLike.setLikeUserId(userLikeId);
            //2.3 调用方法保存
            mongoTemplate.save(userLike);
        }


    }

    /**
     * 判断用户是否相互喜欢
     * @param loginUserId
     * @param userLikeId
     * @return
     */
    @Override
    public boolean isUserLike(Long loginUserId, Long userLikeId) {
        //1.我是否喜欢对方
        Query query1 = new Query(
                Criteria.where("userId").is(loginUserId)
                        .and("likeUserId").is(userLikeId)
        );
        boolean flag1 = mongoTemplate.exists(query1, UserLike.class);
        //2.对方是否喜欢我
        Query query2 = new Query(
                Criteria.where("userId").is(userLikeId)
                        .and("likeUserId").is( loginUserId)
        );
        boolean flag2 = mongoTemplate.exists(query2, UserLike.class);
        return flag1 && flag2;
        //return 变量>0; 查看是否有记录
    }



    //删除喜欢关系(我不在喜欢她)
    @Override
    public void delete(Long userId, Long likeUserId) {
        //删除我喜欢她
        mongoTemplate.remove(
                new Query(Criteria.where("userId").is(userId)
                        .and("likeUserId").is(likeUserId)), UserLike.class);
    }
}